{% extends "base.html" %}
{% load staticfiles %}

{% block title %}策略管理{% endblock %}

{% block styles %}

{% endblock %}

{% block content %}

    <section class="content-header">
        <h1>
            策略管理
            <small>{{ allHtml.title }}</small>
        </h1>
    </section>

    <!-- Main content -->
    <section style="overflow:auto" class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="nav-tabs-custom">
                    <div class="tab-content ">
                        <div class="tab-pane active mailbox-messages" id="fa-icons">
                            <div class=" mailbox-messages">
                                <table class="table table-bordered table-striped table-hover" id="StrategyTable">

                                </table>
                            </div>
                        </div>
                        <div class="tab-pane" id="glyphicons">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!--策略名称点击弹出框（查看策略详情信息）-->
    <div class="modal fade" id="modal_code_list">
        <div class="modal-dialog" style="width: 700px;height:300px">
            <div class="modal-content">
                <div class="modal-body" style="padding:30px;height:295px;">
                    <div class="block margin-bottom-sm">
                        <div class="title"><strong>策略代码列表</strong></div>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>更新时间</th>
                                    <th>备注</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--新建策略点击弹出框-->
    <div class="modal fade" id="modal_new_strategy">
        <div class="modal-dialog" style="width: 600px;height:700px">
            <div class="modal-content">
                <div class="m-head">
                <span class="new_strategy title">
                    新建策略 : 基本信息
                </span>
                </div>
                <div class="modal-body" style="padding: 30px;height:auto;">
                    <div id="base_info">
                        <div class="v input-group">
                        <span class="input-group-addon">
                            策略ID&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                        </span>
                            <input class="form-control" type="text" id="strategy_id">
                        </div>
                        <div class="v input-group">
                        <span class="input-group-addon">策略名称&nbsp&nbsp&nbsp
                        </span>
                            <input class="form-control" type="text" id="strategy_name">
                        </div>
                        <div class="v input-group">
                        <span class="input-group-addon">债券代码&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                        </span>
                            <input class="form-control" type="text" id="param_instrument">
                        </div>
                        <div class="v input-group">
                        <span class="input-group-addon">行情起始时间
                        </span>
                            <input placeholder="yyyy-mm-dd" class="form-control" type="text"
                                   id="param_start_date">
                        </div>
                        <div class="v input-group">
                        <span class="input-group-addon">行情结束时间
                        </span>
                            <input placeholder="yyyy-mm-dd" class="form-control" type="text"
                                   id="param_end_date">
                        </div>
                    </div>
                    <div id="btns" align="right">
                        <button class="btn-success opt" onclick="next_step()">确定</button>
                        <button class="btn-success" onclick="$('#modal_new_strategy').modal('hide');modal_clear();">取消
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        .w {
            margin-top: 10px;
        }

        .file {
            position: relative;
            display: inline-block;
            background: #D0EEFF;
            border: 1px solid #99D3F5;
            border-radius: 4px;
            padding: 4px 12px;
            overflow: hidden;
            color: #1E88C7;
            text-decoration: none;
            text-indent: 0;
            line-height: 20px;
        }

        #td1 td {
            font-size: 15px;
            width: 50px;
        }

        .file input {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
        }

        .file:hover {
            background: #AADFFD;
            border-color: #78C3F3;
            color: #004974;
            text-decoration: none;
        }

        .out {
            width: 100%;
        }

        .xx {
            margin-left: 10px;
            width: 70%;
            float: right;
        }

        .l {
            width: 80%;
            float: left;
            margin-top: 10px;
        }

        .r {
            width: 15%;
            float: left;
            margin-top: 10px;
            margin-left: 15px;
        }

        .v {
            margin-top: 30px;
            margin-bottom: 30px;
        }

        .new_strategy {
            border-style: solid;
            border-width: 1px;
            padding: 10px;
            border-color: #eee;
        }

        .m-head {
            padding-top: 20px;
            padding-left: 20px;
        }

        .choices {
            border-style: solid;
            border-width: 1px;
            padding: 10px;
            border-color: #eee;
            padding-left: 40px;
            width: 400px;
            height: 200px;
            color: #665544;
        }

        .td {
            border-color: #eee
        }


    </style>

{% endblock %}

{% block scripts %}


    <script type="text/javascript">
        function quit() {
            $('#modal_c').modal('hide');
        }

        var code_file = {};


        function flush_input() {
            if ($('#StgFile').val() && (!$('.StgFile').val())) {
                $('.StgFile').val($('#StgFile').val());
            }
            if ($('#StgConFile').val() && (!$('.StgConFile').val())) {
                $('.StgConFile').val($('#StgConFile').val());
            }
            if ($('#CodeFile').val() && (!$('.CodeFile').val())) {
                $('.CodeFile').val($('#CodeFile').val());
            }
        }



        setInterval("flush_input()", 300);


        //新建策略，模态框show后触发的事件(shown.bs.modal)
        $('#modal_new_strategy').on('shown.bs.modal', function () {
            // ajax获取策略ID
            $.get("{% url 'Strategy:get_strategy_id' %}", function (r) {
                $('#strategy_id').val(r);
                $('#strategy_id').attr('disabled', 'disabled');
            })
        })
        $('#param_start_date').datetimepicker({
            format: 'yyyy-mm-dd',
            startView: 'year',
            maxView: 'year',
            minView: 'month',
            autoclose: true,
            pickerPosition: "bottom-left",
            language: 'zh',
        });
        $('#param_end_date').datetimepicker({
            format: 'yyyy-mm-dd',
            startView: 'year',
            maxView: 'year',
            minView: 'month',
            autoclose: true,
            pickerPosition: "bottom-left",
            language: 'zh',
        });

        function modal_clear() {
            $('.title').text('新建策略 : 基本信息');
            $('#base_info').css('display', 'block');
            $('#param').css('display', 'none');
            $('#prev').remove();
            $('.modal input').val('');
            $("input[name='uexch']").removeAttr('checked');
            $('.modal input').removeAttr('disabled');
            $('#exch_info').text('');
            {#$('#init_margin').css('display', 'none');#}
        }


        function generate_file(pars) {
            function dozip(f1, c1, f2, c2) {
                var zip = new JSZip();
                zip.folder(pars['StgName']).file(f1, c1).file(f2, c2);
                zip.generateAsync({type: "blob"})
                    .then(function (content) {
                        // see FileSaver.js
                        saveAs(content, pars['StgName'] + ".zip");
                    });
            }

            var config_str = [
                "[strategy_mode]",
                "Run_Mode = 1",
                "StgID = " + pars['StgID'],
                "StgName = " + pars['StgName'],
                "# 1回测 2模拟 3仿真 4实盘	",
                "[strategy_back]",
                "Log_Level = 2",
                "User_ID = " + pars['User_ID'],
                "Market_Host = 111.231.16.33",
                "Market_Port = 27019",
                "#Strategy_Host = 47.102.219.52",
                "Strategy_Host = 111.231.16.33",
                "Strategy_Port = 27019",
                "Start_Time = " + pars['Start_Time'],
                "End_Time = " + pars['End_Time'],
                "Frequency = " + pars['Frequency'],
                "Fields = ",
                "AccountID = " + pars['Acc'],
                "Initial_Fund = " + pars['Initial_Fund'],
                "\n",
                "[strategy_sim]",
                "Log_Level = 2",
                "User_ID = " + pars['User_ID'],
                "Market_Host = 47.102.219.52",
                "Market_Port = 27019",
                "Start_Time = " + pars['Start_Time'],
                'End_Time = ' + pars['End_Time'],
                "Frequency = " + pars['Frequency'],
                "Password = 1",
                "Con_Path = sim_con\\",
                "SIM_Address_IP = tcp://127.0.0.1:22201",
                "\n",
                "[strategy_hft]",
                "HFT_Address_IP = 180.168.146.187:10110"
            ];
            var py_str = [
                "from strategy_mode import *",
                "\n\n",
                "class strategy(strategy_mode):",
                "\n",
                "\tdef __init__(self):",
                "\t\tsuper(strategy, self).__init__()",
                "\t\tself.symbol = ['" + pars['Symbol'] + "']",
                "\t\tself.exchange = " + "'" + pars['Exchange'] + "'",
                "\t\tself.subscribe(self.symbol)",
                "\n",
                "\tdef on_bar(self, data):",
                "\t\tpass",
                "\n",
                "\tdef on_order(self, data):",
                "\t\tpass",
                "\n",
                "\tdef on_trade(self, data):",
                "\t\tpass",
                "\n\n",
                "if __name__ == '__main__':\n\tmain = strategy()"
            ];
            dozip(pars['StgName'] + '.conf', config_str.join('\n'), pars['StgName'] + '.py', py_str.join('\n'))
        }

        function code_list(sid) {
        }


        //获取数据
        function getvalue() {
            data = {
                strategy_id: $("#strategy_id").val(),
                strategy_name: $("#strategy_name").val(),
                param_instrument: $("#param_instrument").val(),
                param_start_date: $("#param_start_date").val(),
                param_end_date: $("#param_end_date").val(),
            }
            return data;
        }

        //数据校验
        function checkvalue() {
            var valueDict = getvalue();
            var flag = 1;
            for (let key in valueDict) {
                if (Boolean(valueDict[key]) == true) {
                    continue
                } else {
                    $('#' + key).attr('placeholder', '请输入' + $('#' + key).prev().text());
                    flag = 2
                }
            }
            if ($('#param_start_date').val() > $('#param_end_date').val()) {
                $('#param_end_date').val('');
                $('#param_end_date').attr('placeholder', '策略结束时间不能小于策略开始时间');
                flag = 2
            }
            if (flag === 2) {
                return 'n'
            } else {
                return 'y'
            }
        }

        function next_step() {
            //校验数据
            var flag = checkvalue()
            if (flag === 'n') {
                return;
            } else {
                // 客户端生成两个配置文件
                var pars = {
                    StgName: $('#strategy_name').val(),
                    User_ID: $('#strategy_id').val().split('_')[0],
                    StgID: $('#strategy_id').val(),
                    Acc: $('input[name="acc"]').map(function () {
                        return $(this).val()
                    }).get().toString(),
                    Initial_Fund: $('input[name="cash"]').map(function () {
                        return $(this).val()
                    }).get().toString(),
                    Start_Time: $('#param_start_date').val(),
                    End_Time: $('#param_end_date').val(),
                    Frequency: $('input[name="freq"]').val(),
                    Symbol: $('#param_instrument').val(),
                    Exchange: $('#param_exchange').val()
                }
                generate_file(pars);
                $('#modal_new_strategy').modal('hide');
                var StgID = $('#strategy_id').val();
                var StgName = $('#strategy_name').val();
                // 清空数据 重置到base_info
                modal_clear();
                // 写入数据库
                console.log(StgID, StgName);
                $.post("{% url 'Strategy:back_strategy_insert' %}", {'StgID': StgID, 'StgName': StgName});
                location.reload();
                return;
            }
        }

        function new_strategy() {
            $('#modal_new_strategy').modal('show');
        }


        //对页面进行渲染，主要是table,tr渲染数据
        var tableName = "StrategyTable";
        //去掉'<button class="btn-success" style="margin-left:10px;" onclick="display()">展示全部策略</button>   ' +
        var lengthMenu = '<span>策略名称 </span><input class="stgname" type="text" id="sid">' +
            '<button class="btn-suc" onclick="gets()">查询</button>' +
            '<button class="btn-suc" onclick="new_strategy()">新建策略</button>';
        var urlParam = "{% url 'Strategy:strategy_list' %}";
        var columnsParam = [
            {title: "策略id", data: "StrategyID"},
            {title: "策略名称", data: "StrategyName"},

            {
                title: "创建时间",
                data: "CreateDateTime",
            },
            {title: "最新回测时间", data: "LatestBackTestDateTime"},
            {title: "仿真审批状态", data: "sim_approval_status", sClass: 'hidden'},
            {title: "策略状态", data: "Status", sClass: "hidden"},
            {
                title: "回测次数", data: null, sClass: 'operation',
                "render": function (data, type, full, meta) {
                    if (data.BackTestCount == "0") {
                        return "0";
                    } else {
                        var userModify = "<a  href='{% url 'Strategy:backtest' %}" + "?strategyId=" + data.StrategyID + "'>" + data.BackTestCount + " &nbsp</a>";
                        return userModify;
                    }
                }
            },
        ];
        var userdataTable = initdataTable(tableName, lengthMenu, urlParam, columnsParam, null, "");

        //展示全部策略
        function display() {
            $('#' + tableName).dataTable().fnDestroy();
            {#var userTable = initdataTable(tableName, lengthMenu, urlParam, columnsParam, msid);#}
            initdataTable(tableName, lengthMenu, urlParam, columnsParam, null, "");
        }

        //点击查询的逻辑代码
        function gets() {
            let msid = $('#sid').val();
            $('#' + tableName).dataTable().fnDestroy();
            {#var userTable = initdataTable(tableName, lengthMenu, urlParam, columnsParam, msid);#}
            initdataTable(tableName, lengthMenu, urlParam, columnsParam, msid, "");
            //上面两种写法实现效果一样。
        }


    </script>
{% endblock %}